/**
 * 菜单工具类
 */

export default function buildMenus (menus, routeMapping) {
  if (menus) {
    let returnMenus = []
    menus.forEach(function (item) {
      let menu = {
        id: item.id,
        keyId: item.id,
        title: item.name,
        component: item.component,
        path: item.href,
        params: null,
        query: {},
        parentId: item.parentId,
        leaf: true,
        hidden: false,
        icon: item.icon,
        children: [],
        menuCode: item.menuCode,
        operationList: []
      }
      if (!item.component) {
        item.component = routeMapping[item.path]
      }
      if (item.params) {
        menu.params = JSON.parse(item.params)
      }
      if (item.query) {
        menu.query = JSON.parse(item.query)
      }
      if (item.hidden !== null && item.hidden !== undefined) {
        menu.hidden = item.hidden
      }
      if (item.leaf !== null && item.leaf !== undefined) {
        menu.leaf = item.leaf
      }
      if (item.menuCode !== null && item.menuCode !== undefined) {
        menu.menuCode = item.menuCode
      }
      if (item.opAuthorityDTOList !== null && item.opAuthorityDTOList !== undefined) {
        menu.operationList = item.opAuthorityDTOList
      }
      if (item.parentId === '0') {
        returnMenus.push(menu)
      } else {
        // 子菜单
        // 查询对应的父级菜单，并添加到父级菜单下
        returnMenus.forEach(m => {
          if (m.keyId === item.parentId) {
            m.leaf = false
            m.children.push(menu)
            return
          }
          if (!m.leaf) {
            m.children.forEach(sm => {
              if (sm.keyId === item.parentId) {
                sm.leaf = false
                sm.children.push(menu)
              }
            })
          }
        })
      }
    }, this)
    return returnMenus
  }
  return []
}
